from datetime import datetime
import os
import tempfile
import threading
import uuid
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import redis
import requests
from reportservice.helpers import ApiResponse
import json
from .yida_config import YidaClient
from yida_app_service.models import JgData
from yida_app_service.utils.common_utils import timestamp_ms_to_date
from django.db import transaction
from doc_service.utils import merge_pdfs
from oss_service.views import bucket
from shutil import rmtree
import time
import logging
yida_client = YidaClient()
logger = logging.getLogger(__name__)
# org_id = "0D30B9A789B6454CBCAAF80380CB9809"
admin_user_id = "6821270455650770"
r = redis.StrictRedis(host='10.8.0.83', port=6379, db=0)

contract_form_id = "FORM-50450F2F696E467DAF0A99C15BF62A5AROMB"
wt_form_id = "FORM-2CE1B37D96B64E24A0C6659C5FA7F25BDJW3"
jg_test_form_id ="FORM-A0B90C1F66044A19B7E4C9A087CA6C6BH8MS"
report_form_id = "FORM-686A7975279942B692D9C82E4D5FAE31YP3M"
billing_apply_form_id  = "FORM-24BB749E5D744FBDBE5107738ECA04258LF0"
company_name = "zhongji"


@csrf_exempt
@require_http_methods(["GET"])
def get_contract_no(request):
    area = request.GET.get('area')
    detection_type = request.GET.get('detection_type')
    form_inst_id = request.GET.get('form_inst_id')
    current_year = datetime.now().year % 100
    
    if detection_type == "地基基础类" or detection_type=="桥梁及地下工程":
        data = yida_client.get_form_data_by_search_field("FORM-50450F2F696E467DAF0A99C15BF62A5AROMB",
                                                        admin_user_id,
                                                {
                                                    "selectField_ltmafgc5":detection_type,
                                                    "selectField_ltmafgcb":area
                                                },current_page=1,page_size=2
                                                )
    else:
        data = yida_client.get_form_data_by_search_field("FORM-50450F2F696E467DAF0A99C15BF62A5AROMB",
                                                        admin_user_id,
                                                {
                                                    "selectField_ltmafgc5":detection_type,
                                                    
                                                },current_page=1,page_size=2
                                                )
    if len(data)==2:
        form_data = data[1].form_data
        last_contract_no = form_data['textField_ltcftb8e']
        if detection_type == "地基基础类":
            type_code = last_contract_no[5:8]
        elif detection_type == "结构（评估、监测）":
            type_code = last_contract_no[5:9]
        else:
            type_code = last_contract_no[5:7]
        previous_year = int(last_contract_no[-6:-4])
        serial_number_string = last_contract_no[-4:]
        if current_year != previous_year:
            serial_number = 1 
        else:
            serial_number = int(serial_number_string)+1

    else:
        if detection_type == "地基基础类": 
            areaMap1 = {
                "杭州": "DJA",
                "宁波": "DJB",
                "温州": "DJC",
                "绍兴": "DJD",
                "湖州": "DJE",
                "衢州": "DJF",
            }

            type_code = areaMap1.get(area, "")
        elif detection_type == "桥梁及地下工程":
            areaMap2 = {
                "杭州": "QA",
                "杭州以外地区": "QB",
                "桥梁定检": "QC",   
            }
            type_code = areaMap2.get(area, "")
        else:
            detailTypeMap = {
                "结构（混凝土结构、砌体结构等）": "JG",
                "鉴定结构（仅用于鉴定报告）": "JG",
                "结构（评估、监测）":"JGPG",
                "结构监测": "YC",
                "钢构（所有钢结构现场检测）": "GG",
                "金属材料（所有钢结构实验室检测）": "JS",
                "地基基础鉴定（仅用于鉴定报告）": "DJ",
                "管道（CCTV管道）": "GD",
                "司法（司法鉴定报告）": "SF",
                "危房（危房鉴定报告）": "WF",
                "比对（比对报告，能力验证报告等）": "BD",
                "典型（新增扩项项目等报告）": "DX",
                "评审（专家现场评审报告）": "PS",
                "管理类（内务等管理文件）": "GL",
                "建筑材料": "JZ",
                "市政材料": "SZ",
            }
            type_code = detailTypeMap.get(detection_type, "")
        serial_number=1

    contract_no = f"ZJWT/{type_code}{current_year:02d}{serial_number:04d}" 

    yida_client.update_form_data_by_id("FORM-50450F2F696E467DAF0A99C15BF62A5AROMB",admin_user_id,form_inst_id,
    {
        "textField_ltcftb8e":contract_no
    })

    return ApiResponse.success(data=contract_no)

@csrf_exempt
@require_http_methods(["GET"])
def get_original_no(request):
    delegation_no = request.GET.get('delegation_no')
    finst_id  = request.GET.get('finst_id')
    type_code = delegation_no[5:7]
    if type_code=='DJ': 
        #DJA,DJB...
        type_code_detail = delegation_no[5:8]
        previous_year = int(delegation_no[8:10])
    elif delegation_no[5:9]=='JGPG':
        type_code = 'PG'
        previous_year = int(delegation_no[9:11])
    else:
        previous_year = int(delegation_no[7:9])
    current_year = datetime.now().year % 100
    typeFormMap={
    "JG": "FORM-A0B90C1F66044A19B7E4C9A087CA6C6BH8MS",
    "PG":"FORM-5AE304E2C9334CC9A6C261F77C28A5AB5BXJ",
    "YC": "",
    "GG": "FORM-CF46208A2FD144E988DFDCDB8DEB865AZPJC",
    "JS": "FORM-4BCC68DEC5DC4D948701442438245EBDPX8E",
    # "DJ": "FORM-57FBC072023E47AEAA8A9DE2B81502BEVMGG",
    # "DJA": "FORM-57FBC072023E47AEAA8A9DE2B81502BEVMGG",
    # "DJB": "FORM-57FBC072023E47AEAA8A9DE2B81502BEVMGG",
    # "DJC": "FORM-57FBC072023E47AEAA8A9DE2B81502BEVMGG",
    # "DJD": "FORM-57FBC072023E47AEAA8A9DE2B81502BEVMGG",
    # "DJE": "FORM-57FBC072023E47AEAA8A9DE2B81502BEVMGG",
    # "DJF": "FORM-57FBC072023E47AEAA8A9DE2B81502BEVMGG",
    # 地基去查找报告信息中记录
    "DJ": "FORM-686A7975279942B692D9C82E4D5FAE31YP3M",
    "DJA": "FORM-686A7975279942B692D9C82E4D5FAE31YP3M",
    "DJB": "FORM-686A7975279942B692D9C82E4D5FAE31YP3M",
    "DJC": "FORM-686A7975279942B692D9C82E4D5FAE31YP3M",
    "DJD": "FORM-686A7975279942B692D9C82E4D5FAE31YP3M",
    "DJE": "FORM-686A7975279942B692D9C82E4D5FAE31YP3M",
    "DJF": "FORM-686A7975279942B692D9C82E4D5FAE31YP3M",
    "GD": "",
    "SF": "",
    "WF": "",
    "BD": "",
    "DX": "",
    "PS": "",
    "GL": "",
    "JZ": "",
    "SZ": "",
    "QA": "FORM-A859477B7E2E417D9C2E32096B77B143UNG0",
    "QB": "FORM-A859477B7E2E417D9C2E32096B77B143UNG0",
    "QC": "FORM-A859477B7E2E417D9C2E32096B77B143UNG0",
  }
    if(type_code=='DJ' ):
        data = yida_client.get_form_data_by_search_field(typeFormMap[type_code],
                                                            admin_user_id,
                                                    {
                                                        'textField_lv36j69f':type_code
                                                    },current_page=1,page_size=2
                
                                                    )
        if len(data)==2:
            form_data = data[1].form_data
            last_original_no = form_data['textField_luc07445']
            serial_number_string = last_original_no[7:11]
            if current_year != previous_year:
                serial_number = 1 
            else:
                serial_number = int(serial_number_string)+1
        else:  
            serial_number=1
        original_no = f"{type_code_detail}JL{current_year:02d}{serial_number:04d}" 

        yida_client.update_form_data_by_id("FORM-686A7975279942B692D9C82E4D5FAE31YP3M",admin_user_id,finst_id,

        {
            "textField_luc07445":original_no
        })
    elif(type_code=='PG' ):
        data = yida_client.get_form_data_by_search_field(typeFormMap[type_code],
                                                    admin_user_id,
                                            {
                                                'textField_lv35j94l':type_code
                                            },current_page=1,page_size=2
        
                                            )  
        if len(data)==2:
            form_data = data[1].form_data
            last_original_no = form_data['textField_lts2ebx5']
            serial_number_string = last_original_no[8:12]
            if current_year != previous_year:
                serial_number = 1 
            else:
                serial_number = int(serial_number_string)+1
        else:  
            serial_number=1

        original_no = f"{type_code}JL{current_year:02d}{serial_number:04d}" 

        yida_client.update_form_data_by_id(typeFormMap[type_code],admin_user_id,finst_id,

        {
            "textField_lts2ebx5":original_no
        })
    else:
        data = yida_client.get_form_data_by_search_field(typeFormMap[type_code],
                                                    admin_user_id,
                                            {
                                                'textField_lv35j94l':type_code
                                            },current_page=1,page_size=2
        
                                            )  
        if len(data)==2:
            form_data = data[1].form_data
            last_original_no = form_data['textField_lts2ebx5']
            serial_number_string = last_original_no[6:10]
            if current_year != previous_year:
                serial_number = 1 
            else:
                serial_number = int(serial_number_string)+1
        else:  
            serial_number=1

        original_no = f"{type_code}JL{current_year:02d}{serial_number:04d}" 

        yida_client.update_form_data_by_id(typeFormMap[type_code],admin_user_id,finst_id,

        {
            "textField_lts2ebx5":original_no
        })

    return ApiResponse.success(data=original_no)

@csrf_exempt
@require_http_methods(["GET"])
def get_report_no(request):
    delegation_no = request.GET.get('delegation_no')
    report_type = request.GET.get('report_type')
    form_inst_id = request.GET.get('form_inst_id')
    type_code = delegation_no[5:7]
    if type_code=='DJ': 
        type_code_detail = delegation_no[5:8]
        previous_year = int(delegation_no[8:10])
    elif delegation_no[5:9]=='JGPG':
        type_code = 'JGPG'
        previous_year = int(delegation_no[9:11])
    else:
        previous_year = int(delegation_no[7:9])
    current_year = datetime.now().year % 100
    data = yida_client.get_form_data_by_search_field("FORM-686A7975279942B692D9C82E4D5FAE31YP3M",
                                                    admin_user_id,
                                            {
                                                'textField_lv36j69f':type_code,
                                                'selectField_luc07447':report_type
                                            },current_page=1,page_size=2
        
                                            )
    if len(data)==2:
        form_data = data[1].form_data
        last_report_no = form_data['textField_ltcjzi71']
        serial_number_string = last_report_no[-4:]
        if current_year != previous_year:
            serial_number = 1 
        else:
            serial_number = int(serial_number_string)+1
    else:  
        serial_number=1
    if(type_code=='DJ'):
        if report_type=='鉴定报告':
            report_no = f"ZJZJ/{type_code_detail}(鉴){current_year:02d}{serial_number:04d}" 
        else:
            report_no = f"ZJZJ/{type_code_detail}{current_year:02d}{serial_number:04d}"
    else:
        if report_type=='鉴定报告':
            report_no = f"ZJZJ/{type_code}(鉴){current_year:02d}{serial_number:04d}" 
        else:   
            report_no = f"ZJZJ/{type_code}{current_year:02d}{serial_number:04d}"
    
    yida_client.update_form_data_by_id("FORM-686A7975279942B692D9C82E4D5FAE31YP3M",admin_user_id,form_inst_id,
    {
        "textField_ltcjzi71":report_no
    })

    return ApiResponse.success(data=report_no)


@csrf_exempt
@require_http_methods(["POST"])
@transaction.atomic
def sys_report_jg_data(request):
        req_data:dict[str,any] = json.loads(request.body)
        report_form_inst_id = req_data.get('report_form_inst_id')
        return create_or_update_jg_data_with_report_info(report_form_inst_id)


"""
查询合同下是否有报告，若有报告，遍历所有报告，更新结构总表数据
若没有报告,则更新or创建结构总表数据(只含合同信息，报告编号为UUID)
若删除合同信息,则删除结构总表中属于该合同的所有数据
"""
@csrf_exempt
@require_http_methods(["POST"])
@transaction.atomic
def sys_contract_jg_data(request):
    req_data = json.loads(request.body)
    contract_form_inst_id = req_data.get('contract_form_inst_id')
    if not contract_form_inst_id:
        return ApiResponse.fail(message="内部错误, form_inst_id为空")
    
    contract_data = yida_client.get_form_items_by_id_list(
        form_uuid=contract_form_id,
        form_inst_id_list=[contract_form_inst_id],
        userId=admin_user_id
    )
    
    if contract_data:
        contract_form_data = contract_data[0].form_data
        contract_id = contract_form_data.get("textField_ltcftb8e", "")
        if contract_id:
            report_data,total= yida_client.get_all_form_data_by_search_field(
                form_uuid=report_form_id,
                userId=admin_user_id,
                search_field=[
                                {
                                  "type": "TEXT",
                                  "operator": "eq",
                                  "componentName": "TextField",
                                  "key": "textField_lts9og36",
                                  "value": contract_id
                                }
                              ]
            )
            if total > 0:
                for item in report_data:
                    if hasattr(item, "form_instance_id"):
                        report_form_inst_id = item.form_instance_id
                        threading.Thread(target=create_or_update_jg_data_with_report_info,args=(report_form_inst_id, contract_form_inst_id)).start()
                JgData.objects.filter(contract_form_inst_id=None).delete()        
                return ApiResponse.success(message="结构合同信息已更新")
            else:
                JgData.objects.filter(contract_form_inst_id=contract_form_inst_id).delete()
                return create_or_update_jg_with_contract_info(contract_form_data, contract_form_inst_id)
        else:
            return ApiResponse.fail(message="合同编号未生成暂时不做同步")
    else:
        JgData.objects.filter(contract_form_inst_id=contract_form_inst_id).delete()
        return ApiResponse.success(message="结构合同信息已删除")


    

def create_or_update_jg_with_contract_info(contract_form_data: dict, contract_form_inst_id: str):
    # 定义将被更新或创建时设置的字段
    defaults = {
        'contract_number': contract_form_data.get("textField_ltcftb8e", ""),
        'contract_date': timestamp_ms_to_date(contract_form_data.get("dateField_ltcftb88")),
        'project_address': get_project_address(contract_form_data),
        'party_a_name': contract_form_data.get("textField_ltnz9jss"),
        'business_type': contract_form_data.get("textField_luxqvzns", ""),
        'unit_price': contract_form_data.get("numberField_ltieok8d"),
        'contract_amount': contract_form_data.get("numberField_lu9gfi4q"),
        'inspector': ", ".join(contract_form_data.get("employeeField_lxlc938n", [])),
        'project_area': contract_form_data.get("selectField_ltmafgcb", ""),
        'contract_salesman': contract_form_data.get("textField_luxqvzns", ""),
        'project_name':contract_form_data.get("textField_ltcftb8j",""),
        'project_leader':contract_form_data.get("employeeField_lv0a8n3g",""),
        'report_form_inst_id': "空报告编号"  # 每次创建都会生成新的 UUID
    }

    # 创建或更新 JgData 实例
    try:
        jg_data = JgData.objects.get(contract_form_inst_id=contract_form_inst_id)
        for key, value in defaults.items():
            setattr(jg_data, key, value)
        jg_data.save()
        return ApiResponse.success(message="结构合同信息同步至结构总表成功")
    except JgData.DoesNotExist:
        jg_data = JgData.objects.create(contract_form_inst_id=contract_form_inst_id, **defaults)
        return ApiResponse.success(message="结构合同信息同步至结构总表成功")
    except Exception as e:
        transaction.set_rollback(True)
        return ApiResponse.fail(message=rf"{e.__str__()}:结构合同信息同步至结构总表失败")
    

def get_jg_data_from_yida(report_form_data: dict, report_form_inst_id: str, contract_form_inst_id: str):
    # 获取合同ID
    contract_id = report_form_data.get("textField_lts9og36")
    if not contract_id:
        return ApiResponse.fail(message="报告信息表的合同编号不完整")
    
    # 从系统中获取合同数据
    contract_data, contract_data_total = yida_client.get_form_data_by_search_field_with_total(
        form_uuid=contract_form_id,
        userId=admin_user_id,
        search_field={"textField_ltcftb8e": contract_id}
    )
    if not contract_data_total:
        return ApiResponse.fail(message="未能找到合同信息")

    # 获取开票申请数据
    bill_apply_data, bill_apply_data_total = yida_client.get_form_data_by_search_field_with_total(
        form_uuid=billing_apply_form_id,
        userId=admin_user_id,
        search_field={"textField_lv1pzi5j": report_form_data.get("textField_ltcjzi71")}  # 报告编号
    )
    bill_apply_form_data = bill_apply_data[0].form_data if bill_apply_data_total else {}

    # 解析合同数据
    contract_form_data = contract_data[0].form_data if contract_data_total else {}

    # 处理附件字段
    try:
        original_record_file = json.loads(report_form_data.get("attachmentField_luc1bveb", "[]"))
    except json.JSONDecodeError:
        original_record_file = []

    # 构建需要更新的字段数据
    update_data = {
        "report_form_inst_id": report_form_inst_id,  # 添加 report_form_inst_id
        "contract_form_inst_id": contract_form_inst_id,  # 添加 contract_form_inst_id
        "contract_number": contract_form_data.get("textField_ltcftb8e", ""),
        "report_issue_date": timestamp_ms_to_date(report_form_data.get("dateField_ltcftb90")),
        "commission_number": report_form_data.get("textField_lts9og37"),
        "original_record_number": report_form_data.get("textField_luc07445"),
        "report_number": report_form_data.get("textField_ltcjzi71"),
        "project_name": contract_form_data.get("textField_ltcftb8j"),
        "project_name_report": report_form_data.get("textField_lxo359ta"),
        "project_address": get_project_address(contract_form_data),
        "contract_date": timestamp_ms_to_date(contract_form_data.get("dateField_ltcftb88")),
        "party_a_name": contract_form_data.get("textField_ltnz9jss"),
        "business_type": contract_form_data.get("textField_luxqvzns", ""),
        "appraisal_report_date": timestamp_ms_to_date(report_form_data.get("dateField_luthxlj7")),
        "appraisal_grade": report_form_data.get("selectField_m0m2389s"),
        "building_area": report_form_data.get("textField_lwookuo7"),
        "unit_price": contract_form_data.get("numberField_ltieok8d"),
        "contract_amount": contract_form_data.get("numberField_lu9gfi4q"),
        "archive_box_number": report_form_data.get("textField_lutg11of"),
        "original_record_attachment": original_record_file[0].get("downloadUrl") if original_record_file else "",
        "contract_mail_date": timestamp_ms_to_date(report_form_data.get("dateField_lut6eno2")),
        "contract_retrieval_date": timestamp_ms_to_date(bill_apply_form_data.get("dateField_lujfh08n")),
        "billing_unit": bill_apply_form_data.get("textField_luji9eza", ""),
        "billing_date": timestamp_ms_to_date(bill_apply_form_data.get("dateField_lus2ubko")),
        "billing_amount": bill_apply_form_data.get("numberField_ltcftb9h", None),
        "inspector": ", ".join(contract_form_data.get("employeeField_lxlc938n", [])),
        "project_leader": contract_form_data.get("employeeField_lv0a8n3g",""),
        "project_area": contract_form_data.get("selectField_ltmafgcb", ""),
        "contract_salesman": contract_form_data.get("textField_luxqvzns", "")
    }

    return update_data


def update_jg_data_from_instance(jg_data, update_data):
    if jg_data is None:
        # 如果 jg_data 为 None，则创建一个新的实例
        jg_data = JgData()  # 确保 JgData 的构造函数允许无参数调用或提供必要的默认参数

    # 遍历新数据字典的所有字段
    for field, value in update_data.items():
        # 排除不应该更新的字段
        if field not in ['_state', 'created_at']:
            # 设置旧实例的字段为新值
            setattr(jg_data, field, value)

    return jg_data


def create_or_update_jg_data_with_report_info(report_form_inst_id:str,contract_form_inst_id:str=None):
    try:
        if not report_form_inst_id:
            return ApiResponse.fail(message="报告的实例ID不能为空")

        jg_data = JgData.objects.filter(report_form_inst_id=report_form_inst_id).first()
        created = False if jg_data else True

        data = yida_client.get_form_items_by_id_list(
            form_uuid=report_form_id,
            form_inst_id_list=[report_form_inst_id],
            userId=admin_user_id
        )

        if data:
            report_form_data = data[0].form_data
            report_number = report_form_data.get("textField_ltcjzi71","缺少报告编号")
            print(rf"同步的报告编号：{report_number}")
            if not contract_form_inst_id:
                contract_data,contract_data_total = yida_client.get_form_data_by_search_field_with_total(form_uuid=contract_form_id,userId=admin_user_id,search_field={
                    "textField_ltcftb8e":report_form_data.get("textField_lts9og36")
                })
                if(contract_data_total):
                    contract_form_inst_id = contract_data[0].form_instance_id


            jg_data_instance = get_jg_data_from_yida(report_form_data, report_form_inst_id,contract_form_inst_id)
            jg_data = update_jg_data_from_instance(jg_data, jg_data_instance)
            JgData.objects.filter(contract_form_inst_id = contract_form_inst_id,report_form_inst_id="空报告编号").delete()
            # 保存更新后的实例到数据库
            jg_data.save()
            if created:
                return ApiResponse.success(message="数据已插入")
            else:
                JgData.objects.filter(contract_form_inst_id=None).delete()
                return ApiResponse.success(message="数据已更新")
        
        elif not data and not created:
            jg_data.delete()
            return ApiResponse.success(message="数据已删除")
        
        return ApiResponse.fail(message="数据同步失败")
    except Exception as e:
        print(f"内部错误：{str(e)}")
        transaction.set_rollback(True)
        return ApiResponse.fail(message=f"内部错误：{str(e)}")
    
def get_project_address(contarct_form_data:dict[str,any]):
    add_data = {}    
    try:
        add_data :dict[str,any]= json.loads(contarct_form_data.get("addressField_lte29we3","{}"))
    except json.JSONDecodeError:
        add_data = {}
    regionInfos = add_data.get("regionText",[])
    project_address = "/".join([info['zh_CN'] for info in regionInfos if 'zh_CN' in info])
    return project_address



@csrf_exempt
@require_http_methods(['POST'])
def batch_print_cl_report(request):
    req_data = json.loads(request.body)
    form_inst_ids = req_data.get('form_inst_ids', [])
    form_uuid = req_data.get('formUuid', "")
    reports_pdf_paths = []
    if form_inst_ids and form_uuid:
        temp_dir = tempfile.mkdtemp()
        try:
            for form_inst_id in form_inst_ids:
                yida_instance = yida_client.get_form_items_by_ids(form_uuid, form_inst_id, admin_user_id)
                form_data = yida_instance[0].form_data
                report_file_url = json.loads(form_data["attachmentField_lti99yal"])[0].get("downloadUrl")
                full_download_url = yida_client.get_full_download_url(admin_user_id, report_file_url).body.result
                with requests.Session() as session:
                    response = session.get(full_download_url)
                    if response.status_code == 200:
                        report_content = response.content
                        temp_report_path = os.path.join(temp_dir, f"{form_inst_id}.pdf")
                        print(f"完整报告文件已存入缓存文件：{temp_report_path}")
                        with open(temp_report_path, 'wb') as temp_file:
                            temp_file.write(report_content)
                        reports_pdf_paths.append(temp_report_path)

            out_path = os.path.join(temp_dir, "AllReports.pdf")
            merge_pdfs(reports_pdf_paths, out_path)
            oss_pdf_key = f"yida-app/{company_name}/{form_uuid}/报告{uuid.uuid4()}.pdf"
            bucket.put_object_from_file(oss_pdf_key, out_path)
            out_url = f"https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/{oss_pdf_key}"
            return ApiResponse.success(data=out_url, message='报告打印成功')
        finally:
            rmtree(temp_dir)
    return ApiResponse.fail('报告打印失败')


@csrf_exempt
@require_http_methods(['POST'])
def batch_create_wt(request):
    try:
        req_data = json.loads(request.body)
        form_inst_id = req_data.get('form_inst_id')
        form_uuid = req_data.get('form_uuid')
        wt_type = req_data.get('wt_type')
        wt_count = int(req_data.get('wt_count')) - 1
        process_code = req_data.get('process_code')
        admin_user_id = req_data.get('admin_user_id')
        if not (form_inst_id and form_uuid and process_code):
            return ApiResponse.fail("必要的表单信息缺失。")
        yida_instance = yida_client.get_form_items_by_ids(form_uuid, form_inst_id, admin_user_id)
        form_data = yida_instance[0].form_data
        water_number = int(form_data.get("numberField_lutjluh9"))
        gc_info = json.loads(json.loads(form_data.get("associationFormField_lqqbd27d_id")))[0]
        max_retries = 3

        # 创建工具函数
        def update_form_data(wt_number, yp_number):
            return {
                **form_data,
                "numberField_lutjluh9": water_number,
                "textField_lqqbd279": wt_number,
                "textField_lqqbd27b": wt_number,
                "textField_lqqbd27a": yp_number,
                "radioField_lz2agi63": "是",
                "textField_lutjluha": str(uuid.uuid4()),
                "employeeField_lyxzlrkg": [form_data["employeeField_lyxzlrkg_id"][0]],
                "employeeField_lzgmxlgm":[form_data["employeeField_lzgmxlgm_id"][0]],
                "associationFormField_lqqbd27d": [gc_info],
                "numberField_lzdv1qkq":1,
            }

        def create_instance(wt_number, yp_number):
            retries = 0
            while retries < max_retries:
                try:
                    form_update = update_form_data(wt_number, yp_number)
                    yida_client.create_process_instance(form_uuid, admin_user_id, form_update, process_code)
                    return True
                except Exception as e:
                    logger.error(f"创建委托{wt_number}失败，重试次数：{retries}，错误：{str(e)}")
                    retries += 1
                    time.sleep(1)
            logger.info(f"委托编号 {wt_number} 创建失败，已达到最大重试次数。")
            return False

        # 主逻辑区分
        if wt_type == "多份委托":
            for i in range(wt_count):
                report_code = form_data.get("textField_lz0xuukr")
                water_number += 1
                wt_number = f"{report_code}{water_number:04}"
                yp_number = wt_number + "01"

                if not create_instance(wt_number, yp_number):
                    return ApiResponse.fail(f"委托编号 {wt_number} 创建失败")
            return ApiResponse.success(message="批量创建多份委托成功")

        elif wt_type == "多份样品":
            wt_number = form_data.get("textField_lqqbd279")
            for i in range(wt_count):
                index = i + 2
                yp_number = f"{wt_number}{index:02}"

                if not create_instance(wt_number, yp_number):
                    return ApiResponse.fail(f"样品编号 {yp_number} 创建失败")
            return ApiResponse.success(message="批量创建多份样品成功")

    except json.JSONDecodeError:
        return ApiResponse.fail("JSON格式错误")
    except Exception as e:
        logger.error(f"处理请求时发生错误：{str(e)}")
        return ApiResponse.fail("服务器内部错误")